package agenda.extra;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;

import agenda.scheduling.Interval;

/**
 * @author sPeC!
 *
 */
public class Settings {
	
	public final static String DATE_HOUR_FORMAT = "dd/MM/yyyy HH:mm";
	public final static String DATE_FORMAT = "dd/MM/yyyy";
	public final static String TIME_FORMAT = "HH:mm";
	
	
	// Database
	public final static String DATABASE_NAME = "data.dat";
	public final static String TABLE_AULAS_NAME = "Aula";
	public final static String TABLE_TRABALHOS_NAME = "Trabalho";
	public final static String TABLE_EVENTOS_NAME = "Evento";
	
	public final static int DEFAULT_HOURS = 8;
	
	static private GregorianCalendar lastRefresh=null;
	static private int workHours=-1;
	
	public static int getWorkHours() {
		if(workHours==-1)
			loadSettings();
		return workHours;
	}

	public static void setWorkHours(int workHours) {
		Settings.workHours = workHours;
		saveSettings();
	}

	static public GregorianCalendar getLastRefresh()
	{
		if(lastRefresh==null)
			loadSettings();
		return lastRefresh;
	}
	
	static public void setLastRefresh(GregorianCalendar lr)
	{
		lastRefresh=lr;
		saveSettings();
	}
	
	static public void loadSettings()
	{
		String thisLine;
		try {
			BufferedReader br = new BufferedReader(new FileReader("settings.config"));
		    if((thisLine = br.readLine()) != null)
		    {
		    	Date d = Utils.stringToDate(thisLine);
		    	lastRefresh = (GregorianCalendar) GregorianCalendar.getInstance();
		    	lastRefresh.setTime(d);
		    	Interval.clearDate(lastRefresh);
		    }
		    if((thisLine = br.readLine()) != null)
		    {
		    	workHours = Integer.parseInt(thisLine);
		    }
		    br.close();
		}
		catch (IOException e) {
			workHours=DEFAULT_HOURS;
			lastRefresh = Interval.clearDate((GregorianCalendar) GregorianCalendar.getInstance());
		}
	}
	
	static public void saveSettings()
	{
		if(lastRefresh==null)
			lastRefresh = Interval.clearDate((GregorianCalendar) GregorianCalendar.getInstance());
		if(workHours==-1)
			workHours=DEFAULT_HOURS;
		try {
			BufferedWriter br = new BufferedWriter(new FileWriter("settings.config"));
			
			br.write(Utils.dateToString(lastRefresh.getTime()));
			br.write("\r\n");
			br.write(String.valueOf(workHours));

			br.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("fsdfsd");
			e.printStackTrace();
		}
	}
	
	static public void reset()
	{
		lastRefresh = Interval.clearDate((GregorianCalendar) GregorianCalendar.getInstance());
		workHours=DEFAULT_HOURS;
		saveSettings();
	}
	
}
